package br.com.controllcivil.relatorio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import controllcivil.util.DataUtil;
import controllcivil.util.StringUtil;

public class RelatorioUtil {
	
	public static final int PDF = 1;
	
	public static JasperPrint imprimirRelatorio(String arquivoJasper, 
										Map<String, Object> parameters, 
										List<?> list) throws Exception{
		
		JasperPrint jasperPrint = null;
		jasperPrint = JasperFillManager.fillReport(
				arquivoJasper,
				parameters,
				new JRBeanCollectionDataSource(list));

		return jasperPrint;
		
	}
	
	
	public static void exportarParaPDF(JasperPrint jasperPrint, String nomeRelatorio) throws JRException, IOException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		JRPdfExporter exporter = new JRPdfExporter();
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
		exporter.exportReport();
		String hoje =  DataUtil.converteParaString(new Date());
		hoje = StringUtil.substituirCaracter(hoje, "/","_");
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		byte[] bytes = baos.toByteArray();
			
		if (bytes != null && bytes.length > 0) {		
			HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
			response.setContentType("application/pdf");
			response.setHeader("Content-disposition", "attachment; filename= "+ nomeRelatorio +"_" + hoje +"");
			response.setContentLength(bytes.length);
			response.getOutputStream().write(bytes);
			response.getOutputStream().flush();
			response.getOutputStream().close();
			
			facesContext.responseComplete(); 
			facesContext.renderResponse();
	            


		}
	}
	
	

}
